﻿<%@ Page Title="Map" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="Map.aspx.vb" Inherits="WRDBWeb.GISMap" culture="auto" meta:resourcekey="PageResource1" uiculture="auto" MaintainScrollPositionOnPostback="false" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
    <link rel="stylesheet" href="http://js.arcgis.com/3.14/esri/css/esri.css">
    <script src="http://js.arcgis.com/3.14/"></script>
</asp:Content>

<asp:Content ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent" runat="server">
    <section class="featured">
        <div class="content-wrapper">
            <table style="width: 100%">
                <tr>
                    <td>
                        <hgroup class="title">
                            <h1><asp:Label ID="lblPageTitle" runat="server" Text="Map" meta:resourcekey="lblPageTitleResource1"></asp:Label></h1>
                            <h2><asp:Label ID="lblInfo" runat="server" Text="A total of ? records are selected and available for mapping." meta:resourcekey="lblInfoResource1"></asp:Label></h2>
                        </hgroup>
                    </td>
                    <td>
                        <asp:Image ID="Image1" runat="server" ImageAlign="Right" ImageUrl="~/Images/globe_32xLG.png" meta:resourcekey="Image1Resource1" />
                    </td>
                </tr>
            </table>
        </div>
     </section>
</asp:Content>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server" >

<script>

    dojo.require("dijit.layout.BorderContainer");
    dojo.require("dijit.layout.ContentPane");
    dojo.require("esri.map");
    dojo.require("esri.toolbars.draw");
    dojo.require("esri.arcgis.utils");

    $(document).ready(dojo.addOnLoad(LoadMap));

    var Stations; //Station_ID, Station_Name, Lat, Long, Result, Size
    var map;

    function LoadMap() {
        var mapURL = $("[id$='hdnMapURL']").val()
        if (mapURL == null) return null;
        OnLoadMap(mapURL);
    }

    function OnLoadMap(mapURL) {

        showProgress();

        if (mapURL.indexOf("http") == 0) {
            //retrieve map from ACP map server
            map = new esri.Map("map", {
                wrapAround180: true,
                //center: [-79.75, 9.15],
                //zoom: 10,
                fadeOnZoom: true,
                showAttribution: false,
                nav: false,
                slider: true,
                sliderStyle: "small"
            });

            map.on("load", RefreshMap);
            map.on("error",function () {alert('An error has occurred while trying to load the map: ' + mapURL)});
            layer.on("error", function () { alert('An error has occurred while trying to load the layer: ' + mapURL) });

            var layer = new esri.layers.ArcGISDynamicMapServiceLayer(mapURL);

            if (layer.loaded) {
                map.addLayer(layer);
            }
            else {
                map.on("load", map.addlayer(layer));
            };
        }

        else if (mapURL == "streets" ||
                 mapURL == "satellite" ||
                 mapURL == "hybrid" ||
                 mapURL == "topo" ||
                 mapURL == "gray" ||
                 mapURL == "oceans" ||
                 mapURL == "national-geographic" ||
                 mapURL == "osm") {
            //retrieve map from ACP map server (note: want to reference jsapi and css files there too)
            //note: this try/catch block does not catch instance of no internet connection
            try {
                map = new esri.Map("map", {
                    basemap: mapURL,
                    wrapAround180: true,
                    center: [-79.75, 9.15],
                    zoom: 10,
                    fadeOnZoom: true,
                    showAttribution: false,
                    nav: false,
                    slider: true,
                    sliderStyle: "small"
                });

                map.on("load", RefreshMap); //preferred way to add event handler
                map.on("error", MapLoadError); //preferred way to add event handler

            }
            catch (e) {
                alert('An error has occurred while trying to load the map: ' + e.message);
            }
        }

        else {
            //use published map on internet
            var mapDeferred = esri.arcgis.utils.createMap(mapURL, "map", {
                mapOptions: {
                    wrapAround180: true,
                    center: [-79.75, 9.15],
                    zoom: 10,
                    fadeOnZoom: true,
                    showAttribution: false,
                    nav: false,
                    slider: true,
                    sliderStyle: "small"
                }
            });

            mapDeferred.addErrback(function (error) {
                alert('Unable to load GIS map from Internet: ' = dojo.toJson(error.message));
            });

            mapDeferred.then(function (response) {
                map = response.map;
                dojo.connect(dijit.byId('map'), 'resize', map, map.resize);
                RefreshMap();
            });
        };

        hideProgress();

    };

    var infoText = "";

    function RefreshMap() {
        var MapType = $("[id$='cboMapType']").val();
        var PCode = $("[id$='cboPCode']").val();
        PageMethods.GetResource("MapInfoText", function (result) {
            infoText = result;
            PageMethods.GetStations(MapType, PCode, OnGetStationsSucceeded, OnGetStationsFailed);
        })
    }

    function OnGetStationsSucceeded(result, userContext, methodName) {

        if (result == null) return;

        Stations = result; //fields are Station ID, Station Name, Latitude, Longitude, Station_Type, Size, [Count, Min, Max, Avg, MinDate, MaxDate, Result]
        var isStationLoc = $("[id$='cboMapType']").val() == "All Station Locations";

        //set size of popup info window
        var infoHeight = 225;
        if (isStationLoc) infoHeight = 125;
        map.infoWindow.resize(350, infoHeight);

        //already retrieved comma-separated items to use for info title and row headings
        var infoTextItem = infoText.split(",")

        //clear prior graphics
        map.graphics.clear();

        //add a symbol at the specified lat/long point obtained from the server
        var srWGS = new esri.SpatialReference(4326);
        var srMap = map.spatialReference;

        //would be best to project all the points in the array and then plot them, but
        //for some reason, the project function fails if more than 17 points are provided
        //an alternative would be to project then plot each point, but that is very slow
        //instead, assume that the map projection is webmercator and use API to directly convert

        if (srMap.wkid == 4326 || srMap.isWebMercator()) {
            for (var i = 0; i < Stations.length; i++) {
                if (srMap.isWebMercator()) {
                    var xy = esri.geometry.lngLatToXY(Stations[i].Longitude, Stations[i].Latitude, true);
                    var pt = new esri.geometry.Point(xy[0], xy[1], srMap);
                }
                else {
                    var pt = new esri.geometry.Point(Stations[i].Longitude, Stations[i].Latitude, srMap);
                }
                var sz = Stations[i].Size;
                var outline = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color("black"), 1);
                var clr = new dojo.Color("red");
                var sty = esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE;
                if (isStationLoc) {
                    sty = esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND
                    var attributes = {
                        Station_ID: Stations[i].Station_ID,
                        Station_Name: Stations[i].Station_Name,
                        Station_Type: Stations[i].Station_Type
                    };
                    var Label = Stations[i].Station_ID;
                    var infoContent = "<table>" +
                                        "<tr><td>" + infoTextItem[1] + ":</td><td>${Station_ID}</td></tr>" +
                                        "<tr><td>" + infoTextItem[2] + ":</td><td>${Station_Name}</td></tr>" +
                                        "<tr><td>" + infoTextItem[3] + ":</td><td>${Station_Type}</td></tr>" +
                                        "</table>"
                }
                else {
                    var attributes = {
                        Station_ID: Stations[i].Station_ID,
                        Station_Name: Stations[i].Station_Name,
                        Station_Type: Stations[i].Station_Type,
                        Count: Stations[i].Count,
                        Minimum: Stations[i].MinResult,
                        Maximum: Stations[i].MaxResult,
                        Average: Stations[i].AvgResult,
                        First_Date: Stations[i].MinDate,
                        Last_Date: Stations[i].MaxDate,
                        Result: Stations[i].Result
                    };
                    var Label = Stations[i].Result;
                    var PCode = $("[id$='cboPCode']").val();
                    var infoContent = "<table>" +
                                        "<tr><td>" + infoTextItem[1] + ":</td><td>${Station_ID}</td></tr>" +
                                        "<tr><td>" + infoTextItem[2] + ":</td><td>${Station_Name}</td></tr>" +
                                        "<tr><td>" + infoTextItem[3] + ":</td><td>${Station_Type}</td></tr>" +
                                        "<tr><td>" + infoTextItem[4] + ":</td><td>${Count}</td></tr>" +
                                        "<tr><td>" + infoTextItem[5] + ":</td><td>${Minimum}</td></tr>" +
                                        "<tr><td>" + infoTextItem[6] + ":</td><td>${Maximum}</td></tr>" +
                                        "<tr><td>" + infoTextItem[7] + ":</td><td>${Average}</td></tr>" +
                                        "<tr><td>" + infoTextItem[8] + ":</td><td>${First_Date}</td></tr>" +
                                        "<tr><td>" + infoTextItem[9] + ":</td><td>${Last_Date}</td></tr>" +
                                        "</table>"
                    sty = esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE;
                };
                var sym = new esri.symbol.SimpleMarkerSymbol(sty, sz, outline, clr);

                var infoTemplate = new esri.InfoTemplate(infoTextItem[0], infoContent);
                
                var s = new esri.Graphic(pt, sym, attributes, infoTemplate);
                map.graphics.add(s);

                //optionally show text label next to symbol
                var fnt = new esri.symbol.Font({
                    size: "6pt",
                    family: "sans-serif"
                });
                var txt = new esri.symbol.TextSymbol({
                    //color: "black",
                    //haloColor: "white",
                    //haloSize: "1px",
                    font: fnt,
                    text: Label,
                    horizontalAlignment: "center",
                    verticalAlignment: "bottom",
                    xoffset: 0,
                    yoffset: sz/2
                })
                var t = new esri.Graphic(pt, txt);
                map.graphics.add(t);
            }
        }
        else {
            PageMethods.GetResource("MapProjectionError", function (res) {
                alert(res);
            });
        }

        $("#divDialogProgress").dialog("close");

    }

    function OnGetStationsFailed(error) {
        alert("Error: " + error.get_message() + "\n" +
              "Stack Trace: " + error.get_stackTrace() + "\n" +
              "Status Code: " + error.get_statusCode() + "\n" +
              "Exception Type: " + error.get_exceptionType() + "\n" +
              "Timed Out: " + error.get_timedOut());
        $("#divDialogProgress").dialog("close");
    };

    //note: I could not get the graph feature to work because the session variable was getting reset

    function showGraph(StationID, PCode) {
        $("[id$='hdnStationID']").val(StationID);
        $("[id$='hdnPCode']").val(PCode);
        $("[id$='btnHidden']").click();
        //__doPostBack('<%= UpdatePanel1.ClientID%>', '');
        return false;
    };

    function OnFailed(error, userContext, methodName) {
        alert("Error: " + error.get_message() + "\n" +
              "Stack Trace: " + error.get_stackTrace() + "\n" +
              "Status Code: " + error.get_statusCode() + "\n" +
              "Exception Type: " + error.get_exceptionType() + "\n" +
              "Timed Out: " + error.get_timedOut());
    };

    function MapLoadError() {
        PageMethods.GetResource("MapLoadError", function (res) {
            alert(res);
        });
    };

</script>

<script>
    //this method requires that the page contain a div called divDialogProgress that looks like this:
    //        <div id="divDialogProgress" title="Please stand by..." style="display:none">
    //          <div id="divProgress"></div>
    //        </div>
    //Will also need the GetResource pagemethod in codebehind
    //It should be called after a button is clicked using OnClientClicked="showProgress(); return true;"

    var dlg;

    function showProgress() {
        $("#divProgress").progressbar({
            value: false //indeterminate
        });

        PageMethods.GetResource("ProgressTitle", function (res) {
            $("#divDialogProgress").attr("title", res);
            dlg = $("#divDialogProgress").dialog({
                modal: true,
                width: 300,
                height: 100,
                resizable: false,
                draggable: false,
                closeOnEscape: false,
                close: function () {$(this).dialog('destroy').remove()} //the dialogs kept getting added and eventually would not close properly (maybe because placed in panel instead of div); this seems to fix it
            })
        })
    };

    function hideProgress() {
        if (dlg) if (dlg.dialog("isOpen") == true) dlg.dialog("close");
    };

</script>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server" >
        <ContentTemplate>
            <div id="divChartCntl" >
                <table style="width:100%">
                    <tr>
                        <td style="vertical-align:middle; width:1px; white-space:nowrap ">
                            <asp:Label runat="server" ID="lblMapName" Style="white-space:nowrap; vertical-align:middle" meta:resourcekey="lblMapNameResource1" Text="Map Name:"></asp:Label>
                        </td>
                        <td style="vertical-align:middle; width:1px; white-space:nowrap ">
                            <asp:DropDownList ID="cboMapSource" runat="server" AutoPostBack="True" meta:resourcekey="cboMapSourceResource1" >
                            </asp:DropDownList>
                        </td>
                        <td style="vertical-align:middle; width:1px; white-space:nowrap ">
                            <asp:Label runat="server" ID="lblMapType" Style="white-space:nowrap; vertical-align:middle" meta:resourcekey="lblMapTypeResource1" Text="Map Type:"></asp:Label>
                        </td>
                        <td style="vertical-align:middle; width:1px; white-space:nowrap ">
                            <asp:DropDownList ID="cboMapType" runat="server" meta:resourcekey="cboMapTypeResource1" AutoPostBack="True">
                                <asp:ListItem meta:resourcekey="ListItemResource1" Value="Maximum Values">Maximum Values</asp:ListItem>
                                <asp:ListItem meta:resourcekey="ListItemResource2">Minimum Values</asp:ListItem>
                                <asp:ListItem meta:resourcekey="ListItemResource3">Average Values</asp:ListItem>
                                <asp:ListItem meta:resourcekey="ListItemResource4">All Station Locations</asp:ListItem>
                            </asp:DropDownList>
                        </td>
                        <td style="width:100%">
                        </td>
                        <td style="vertical-align:middle; width:1px; white-space:nowrap ">
                                <asp:Label runat="server" ID="lblPCode" Style="white-space:nowrap; vertical-align:middle" meta:resourcekey="lblPCodeResource1" Text="PCode: "></asp:Label>
                        </td>
                        <td style="vertical-align:middle; width:1px; white-space:nowrap ">
                                <asp:DropDownList ID="cboPCode" runat="server" Width="15em" AutoPostBack="true" ToolTip="For any Map Type other than Station Locations, this controls what PCode is displayed; the size of the symbol controls the relative magnitude of the selected parameter ." meta:resourcekey="cboPCodeResource1"></asp:DropDownList>
                        </td>
                    </tr>
                </table>
            </div>
            <asp:HiddenField ID="hdnMapURL" runat="server" />
            <asp:HiddenField ID="hdnStationID" runat="server" />
            <asp:HiddenField ID="hdnPCode" runat="server" />
            <hr />

            <div class="claro" dojotype="dijit.layout.BorderContainer" design="headline" gutters="false" style="width: 100%; height: 100%; margin: 0;">
                <div id="map" dojotype="dijit.layout.ContentPane" region="center" style="border: 1px solid #000; padding: 0; height: 500px;">
                </div>
            </div>

        </ContentTemplate>

        <Triggers>
            <asp:PostBackTrigger ControlID="cboMapSource" />
            <asp:PostBackTrigger ControlID="cboMapType" />
            <asp:PostBackTrigger ControlID="cboPCode" />
            <asp:PostBackTrigger ControlID="btnHidden" />
        </Triggers>

    </asp:UpdatePanel>

    <asp:Button ID="btnHidden" runat="server" Text="btnHidden" style="display:none"/>
    <div id="divDialogProgress" title="Please stand by..." style="display:none"><div id="divProgress"></div></div>
    

</asp:Content>

